﻿using Application.Commons.Data;
using FluentMigrator.Runner;
using FrameworkCore.Hubs;
using FrameworkCore.Migrations;
using FrameworkCore.Modules.Engines;
using Microsoft.AspNetCore.Builder;

namespace FrameworkCore.Extensions;

/// <summary>
/// 表示 IApplicationBuilder 的扩展方法集合。
/// </summary>
public static class ApplicationBuilderExtensions
{
    /// <summary>
    /// 配置应用程序的 HTTP 请求管道。
    /// </summary>
    /// <param name="application">用于配置应用程序请求管道的构建器。</param>
    public static void ConfigureRequestPipeline(this IApplicationBuilder application)
    {
        EngineContext.Current.ConfigureRequestPipeline(application);
    }

    /// <summary>
    /// 异步启动引擎。
    /// </summary>
    /// <param name="application">用于启动引擎的构建器。</param>
    public static async Task StartEngineAsync(this IApplicationBuilder application)
    {
        var engine = EngineContext.Current;

        // 仅当数据库已安装时执行进一步操作
        //var dataProvider = engine.Resolve<IAiBLSmartEduDataProvider>();
        //if (dataProvider.DatabaseExists())
        //{
        //    //更新数据库
        //    //var runner = engine.Resolve<IMigrationRunner>();
        //    //if (runner.HasMigrationsToApplyUp())
        //    //{
        //    //    runner.MigrateUp();
        //    //}
        //}
    }

    /// <summary>
    /// 配置端点路由。
    /// </summary>
    /// <param name="application">用于配置应用程序请求管道的构建器。</param>
    public static void UseAiBLSmartEduEndpoints(this IApplicationBuilder application)
    {
        // 执行由路由中间件选择的端点
        application.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

    /// <summary>
    /// 使用静态文件
    /// </summary>
    /// <param name="application"></param>
    public static void UseAiBLSmartEduStaticFiles(this IApplicationBuilder application) 
    {
        application.UseStaticFiles();
    }

    /// <summary>
    /// 配置SignalRHub。
    /// </summary>
    /// <param name="application">即时通讯构建器。</param>
    public static void UseAiBLSmartEduSignalRHub(this IApplicationBuilder application)
    {
        // 执行由路由中间件选择的端点
        application.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<SignalRHub>("/signalRHub");
        });
    }
}
